<style lang="stylus" scoped>

</style>

<template>
  <div>
    <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
      <q-card class="shadow-2">
        <q-card-section class="row justify-between items-center q-py-sm">
          <!-- <q-icon name="fas fa-building" size="40px" color="light-blue"/> -->
          <div class="col-2">
            <q-chip square class="no-border-radius q-ml-none q-mr-none text-weight-bold">
              <q-avatar class="no-border-radius" icon="business" color="light-blue" text-color="white"></q-avatar>
              {{ baseInfoForm.code }}
            </q-chip>
          </div>
          <q-space />
          <q-btn outline label="返回" icon="" color="light-blue" :to="router.router"/>
        </q-card-section>
        <q-separator />
        <q-card-section  class="q-pa-sm">
          <main-field :form="baseInfoForm" :field="fieldConfig"></main-field>
        </q-card-section>
      </q-card>
    </div>
    <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
      <q-card class="shadow-2">
        <q-card-section>
          <q-tabs
            v-model="tabSelected"
            dense
            class="bg-grey-2 text-teal"
            active-color="primary"
            indicator-color="primary"
            align="left"
            narrow-indicator
            @input="tabSelect"
          >
            <q-tab name="tab2" label="地点" />
          </q-tabs>

          <q-tab-panels v-model="tabSelected" animated>
            <q-tab-panel name="tab2">
              <template>
                <q-btn color="light-blue" :label="$t('新增')" @click="add" style="margin-bottom:10px;"/>
              </template>
              <q-table
                flat bordered dense
                class="bg-white"
                :data="siteTableConfig.data"
                :columns="siteTableConfig.columns"
                row-key="id"
                separator="cell"
                selection="multiple"
                :selected.sync="selected"
                :visible-columns="siteTableConfig.visibleColumns"
                :filter="siteTableConfig.filter"
                :pagination.sync="siteTableConfig.pagination"
                :rows-per-page-options="[3, 5, 10, 20]"
                no-data-label="暂无数据"
                table-class="h-custom"
                @request="siteListGet"
              >
                <template v-slot:top-right="props">
                  <q-select
                    v-model="siteTableConfig.visibleColumns"
                    multiple
                    borderless
                    options-dense
                    :display-value="$t('显示列')"
                    emit-value
                    map-options
                    :options="columns"
                    option-value="name"
                    class="q-mx-lg"
                  >
                    <template v-slot:option="scope">
                      <q-item
                        v-bind="scope.itemProps"
                        v-on="scope.itemEvents"
                        v-if="!scope.opt.required"
                      >
                        <q-item-section avatar>
                          <q-toggle color="blue" v-model="siteTableConfig.visibleColumns" :val="scope.opt.name" />
                        </q-item-section>
                        <q-item-section style="min-width:60px">
                          {{ scope.opt.label }}
                        </q-item-section>
                      </q-item>
                    </template>
                  </q-select>
                  <q-toggle
                    v-model="searchToggle"
                    left-label
                    label="搜索"
                    color="blue"
                    checked-icon="check"
                    unchecked-icon="clear"
                    keep-color
                  />
                  <q-btn
                    flat round dense
                    :icon="props.inFullscreen ? 'fullscreen_exit' : 'fullscreen'"
                    @click="props.toggleFullscreen"
                    class="q-ml-md"
                  />
                </template>
                <template v-if="searchToggle" v-slot:top-row="props">
                  <q-tr :props="props">
                    <q-td>
                    </q-td>
                    <q-td v-for="col in props.cols" :key="col.name" class="relative-position">
                      <q-btn class="absolute-center" v-if="col.name==='action'" color="primary" dense flat icon="search" @click="siteListGet({ pagination:siteTableConfig.pagination, filter: siteTableConfig.filter })"/>
                      <q-input dense outlined v-model="siteTableConfig.filter[col.name]" v-else/>
                    </q-td>
                  </q-tr>
                </template>
                <template v-slot:header="props">
                  <q-tr :props="props">
                    <q-th>
                      <q-checkbox indeterminate-value="some" dense v-model="props.selected" />
                    </q-th>
                    <q-th v-for="col in props.cols" :key="col.name" :props="props">
                      {{ col.label }}
                    </q-th>
                  </q-tr>
                </template>
                <template v-slot:body="props">
                  <q-tr :props="props">
                    <q-td width="52">
                      <q-checkbox dense v-model="props.selected" />
                    </q-td>
                    <q-td key="action" :props="props">
                      <q-btn-dropdown
                        color="blue"
                        size="sm"
                        dense
                        menu-anchor="bottom left"
                        menu-self="top left"
                        content-class="text-grey"
                        icon="settings">
                        <q-list dense>
                          <q-item clickable v-close-popup @click="dlow(props.row)">
                            <q-item-section>
                              <q-item-label>删除</q-item-label>
                            </q-item-section>
                          </q-item>
                        </q-list>
                      </q-btn-dropdown>
                    </q-td>
                    <q-td key="siteCode" :props="props">
                      {{ props.row.siteCode  }}
                    </q-td>
                    <q-td key="siteName" :props="props">{{ props.row.siteName }}</q-td>
                    <q-td key="groupName" :props="props">{{ props.row.groupName }}</q-td>
                    <q-td key="typeName" :props="props">{{ props.row.typeName }}</q-td>
                    <q-td key="createTime" :props="props">{{ props.row.createTime }}</q-td>
                  </q-tr>
                  <q-tr v-show="props.expand" :props="props">
                    <q-td colspan="100%">
                    </q-td>
                  </q-tr>
                </template>
                <template v-slot:pagination="props">
                  <q-pagination
                    v-model="siteTableConfig.pagination.page"
                    color="blue"
                    :max-pages="5"
                    :max="siteTablePages"
                    :boundaryLinks="true"
                    :directionLinks="true"
                  />
                  共 {{ siteTableConfig.total }} 条
                </template>
              </q-table>
            </q-tab-panel>
          </q-tab-panels>
        </q-card-section>
      </q-card>
    </div>
    <q-dialog
      v-model="addOrEditDialog"
      persistent
      :maximized="maximizedToggle"
      transition-show="slide-up"
      transition-hide="slide-down">
      <q-card class="bg-white relative-position" style="min-width: 40vw;max-height: 45vw;">
        <q-bar class="bg-white q-py-lg">
          <strong>{{ addOrEdit === 1? '分配地点':''}}</strong>
          <q-space />
          <q-btn dense flat icon="minimize" @click="maximizedToggle = false" :disable="!maximizedToggle">
            <q-tooltip v-if="maximizedToggle" content-class="bg-white text-primary">最小化</q-tooltip>
          </q-btn>
          <q-btn dense flat icon="crop_square" @click="maximizedToggle = true" :disable="maximizedToggle">
            <q-tooltip v-if="!maximizedToggle" content-class="bg-white text-primary">最大化</q-tooltip>
          </q-btn>
          <q-btn dense flat icon="close" @click="addOrEditDialog = false">
            <q-tooltip content-class="bg-white text-primary">关闭</q-tooltip>
          </q-btn>
        </q-bar>
        <q-separator />
        <q-card-section :style="maximizedToggle?'margin-bottom:53px;max-height:83.5vh': 'margin-bottom:53px;min-height:50vh;max-height:60vh'" class="scroll">
          <!-- <q-input
            v-model="filter"
            filled
            placeholder="请输入地点/公司名称"
            clearable
            class="q-mb-sm"
            />
          <q-tree
            :nodes="siteTree"
            color="secondary"
            default-expand-all
            :ticked.sync="ticked"
            :tick-strategy="tickStrategy"
            :filter="filter"
            node-key="id"
            /> -->
          <div class="row q-col-gutter-sm">
             <div class="col-12" style="position: relative;">
              <div  :class="$v.addOrEditForm.typeId.$error?'text-negative': ''">地点</div>
              <q-input
                @keydown="disable=true"
                ref="name"
                :error="$v.addOrEditForm.typeId.$error"
                @blur="$v.addOrEditForm.typeId.$touch"
                v-model="addOrEditForm.siteName"
                dense hint>
                <template v-slot:append>
                  <q-icon name="arrow_drop_down" />
                </template>
              </q-input>
              <div  class="col-12" style="position: relative;top:-100px;height:100%" @click="siteDialog = true"></div>
            </div>
              <div class="col-12">
                <div  :class="$v.addOrEditForm.typeId.$error?'text-negative': ''">品项类型</div>
                <q-select
                emit-value
                map-options
                dense
                @focus="getItemType"
                :error="$v.addOrEditForm.typeId.$error"
                @blur="$v.addOrEditForm.typeId.$touch"
                v-model="addOrEditForm.typeId"
                :options="itemOption" />
              </div>
              <div class="col-12">
                <div  :class="$v.addOrEditForm.groupId.$error?'text-negative': ''">品项组</div>
                <q-select
                emit-value
                map-options
                dense
                @focus="getItemGroupType"
                :error="$v.addOrEditForm.groupId.$error"
                @blur="$v.addOrEditForm.groupId.$touch"
                v-model="addOrEditForm.groupId"
                :options="itemGroupOption" />
              </div>
            <!-- <div class="col-12">
              <h-select-table emit-value required selection="single" field-name="所属地点" url="/mdm/companysite/queryNoPage" :error="$v.addOrEditForm.siteId.$error"   :value="addOrEditForm.siteId" @select="selectSiteRowsHandler"/>
            </div> -->
          </div>
        </q-card-section>
        <q-separator class="absolute" style="bottom: 52px; left: 0"/>
        <q-card-actions align="right" class="absolute-bottom bg-white">
          <q-btn flat label="取消" color="primary" v-close-popup />
          <q-btn flat label="保存" color="primary" :loading="loadingSave" @click="saveHandler" />
        </q-card-actions>
      </q-card>
    </q-dialog>
    <q-dialog
      v-model="siteDialog"
      persistent
      :maximized="maximizedToggle"
      transition-show="slide-up"
      style="max-height:40vw;"
      transition-hide="slide-down">
      <q-card class="bg-white relative-position" style="min-width: 35vw;max-height:35vw;">
        <q-bar class="bg-white q-py-lg">
          <strong>{{ addOrEdit === 1? '选择地点' : '修改地点'}}</strong>
          <q-space />
          <q-btn dense flat icon="minimize" @click="maximizedToggle = false" :disable="!maximizedToggle">
            <q-tooltip v-if="maximizedToggle" content-class="bg-white text-primary">最小化</q-tooltip>
          </q-btn>
          <q-btn dense flat icon="crop_square" @click="maximizedToggle = true" :disable="maximizedToggle">
            <q-tooltip v-if="!maximizedToggle" content-class="bg-white text-primary">最大化</q-tooltip>
          </q-btn>
          <q-btn dense flat icon="close" @click="siteDialog = false">
            <q-tooltip content-class="bg-white text-primary">关闭</q-tooltip>
          </q-btn>
        </q-bar>
        <q-separator />
        <q-card-section id="name" :style="maximizedToggle?'margin-bottom:53px;max-height:83.5vh': 'margin-bottom:53px;min-height:50vh;max-height:60vh'" class="scroll">
          <site url="/mdm/companysite/queryNoPage" @select="selectSiteRowsHandler" :value="addOrEditForm.siteId"></site>
        </q-card-section>
        <q-separator class="absolute" style="bottom: 52px; left: 0"/>
        <q-card-actions align="right" class="absolute-bottom bg-white">
          <q-btn flat label="取消" color="primary" v-close-popup @click="removes"/>
          <q-btn flat label="保存" color="primary" :loading="loadingSave" @click="siteDialog = false" />
        </q-card-actions>
      </q-card>
    </q-dialog>
  </div>
</template>

<script>
import { required } from 'vuelidate/lib/validators'
import MainField from 'src/pages/Common/SecondPackage/MainField/MainField'
// import axios from 'axios'
// import Qs from 'qs'
import site from 'pages/Mdm/Item/site'
// import HSelectTable from 'components/Common/SiteTable'
export default {
  name: 'disSite',
  components: {
    // HSelectTable,
    site,
    MainField
  },
  data () {
    return {
      siteDialog: false,
      searchToggle: false,
      searchForm: {
        name: '',
        code: '',
        createTime: ''
      },
      disable: false,
      addOrEditForm: {
        groupId: '',
        typeId: '',
        siteId: '',
        siteName: ''
      },
      fieldConfig: [
        {
          name: 'name',
          label: '名称'
        },
        {
          name: 'createUserName',
          label: '创建人'
        },
        {
          name: 'createTime',
          label: '创建时间'
        },
        {
          name: 'lastUpdateTime',
          label: '上次更新时间'
        },
        {
          name: 'remark',
          label: '说明',
          type: 'textarea'
        }
      ],
      siteTree: [],
      selected: [],
      ticked: [],
      tickStrategy: 'leaf',
      visibleColumns: [
        'action',
        'name',
        'code',
        'createTime'
      ],
      // 当加入 required: true 属性时  visibleColumns 对当前字段无效
      columns: [
        { name: 'code', required: true, label: '地点编码', align: 'left', field: 'code', sortable: true },
        { name: 'name', required: true, label: '地点名称', align: 'left', field: 'name', sortable: true },
        { name: 'createTime', field: 'createTime', align: 'left', label: '创建时间', sortable: true }
      ],
      data: [],
      companySite: {},
      total: 0,
      pagination: {
        page: 1,
        rowsPerPage: 10,
        rowsNumber: 10,
        sortBy: '',
        descending: Boolean
      },
      id: '',
      addOrEdit: 1,
      maximizedToggle: false,
      addOrEditDialog: false,
      loadingSave: false,
      baseInfoForm: {
        name: '',
        code: '',
        nameEn: '',
        createUserName: '',
        createTime: '',
        lastUpdateTime: '',
        remark: ''
      },
      itemGroupOption: [],
      itemOption: [],
      tabSelected: 'tab2',
      siteTableConfig: {
        // 当加入 required: true 属性时  visibleColumns 对当前字段无效
        columns: [
          { name: 'action', required: true, label: '操作', align: 'center' },
          { name: 'siteCode', required: true, label: '地点编码', align: 'left', field: 'siteCode', sortable: true },
          { name: 'siteName', required: true, label: '地点名称', align: 'left', field: 'siteName', sortable: true },
          { name: 'groupName', required: true, label: '品项组', align: 'left', field: 'groupName', sortable: true },
          { name: 'typeName', required: true, label: '品项类型', align: 'left', field: 'typeName', sortable: true },
          { name: 'createTime', field: 'createTime', align: 'left', label: '创建时间', sortable: true }
        ],
        data: [],
        filter: {
          siteCode: '',
          siteName: '',
          groupName: '',
          typeName: '',
          createTime: ''
        },
        total: 0,
        pagination: {
          page: 1,
          rowsPerPage: 5,
          rowsNumber: 5,
          sortBy: '',
          descending: Boolean
        }
      }
    }
  },
  computed: {
    siteTablePages () {
      return Math.ceil(this.siteTableConfig.total / this.siteTableConfig.pagination.rowsPerPage)
    },
    pages () {
      return Math.ceil(this.total / this.pagination.rowsPerPage)
    },
    router () {
      return this.$store.state.router
    }
  },
  validations: {
    addOrEditForm: {
      typeId: { required },
      groupId: { required },
      siteName: { required }
    }
  },
  watch: {
    'siteTableConfig.pagination.page' () {
      this.siteListGet({
        pagination: this.siteTableConfig.pagination,
        filter: this.siteTableConfig.filter
      })
    },
    'pagination.page' () {
      this.listGet({
        pagination: this.pagination,
        filter: this.searchForm
      })
    },
    'addOrEditDialog' () {
      if (this.addOrEditDialog === true) {
        this.getSideTree()
      }
    }
  },
  mounted () {
    this.id = this.$route.params.id
    this.init()
    this.getItemGroupType()
    this.getItemType()
  },
  methods: {
    removes () {
      this.addOrEditForm.siteId = ''
      this.addOrEditForm.siteName = ''
    },
    // 获取品项类型
    async getItemType () {
      await this.$api({
        method: 'post',
        url: '/common/dict/findByTypeCode/30',
        emulateJSON: true,
        useLoadLayer: true,
        successCallback: ({ data }) => {
          console.log(data)
          let arr = []
          data.forEach(item => {
            let o = {}
            o.label = item.name
            o.value = item.id
            arr.push(o)
          })
          this.itemOption = arr
        }
      })
    },
    // 获取品项组
    async getItemGroupType () {
      await this.$api({
        method: 'post',
        url: '/mdm/item/group/query',
        emulateJSON: true,
        useLoadLayer: true,
        successCallback: ({ data }) => {
          let arr = []
          let datas = data.list
          datas.forEach(item => {
            let o = {}
            o.label = item.name
            o.value = item.id
            arr.push(o)
          })
          this.itemGroupOption = arr
        }
      })
    },
    selectSiteRowsHandler (row) {
      let v = [], l = []
      row.forEach(s => {
        v.push(s.siteId)
        l.push(s.siteName)
      })
      this.addOrEditForm.siteId = v.join(',')
      this.addOrEditForm.siteName = l.join(',')
      console.log(this.addOrEditForm)
    },
    // 删除
    async dlow (prop) {
      console.log(prop)
      await this.$api({
        method: 'post',
        url: `/mdm/item/site/batchDel`,
        params: {
          ids: prop.id
        },
        Qsjson: true,
        useNotify: true,
        successCallback: ({ data }) => {
          this.addOrEditDialog = false
        },
        errorCallback (err) {
          console.log('未处理的业务级error：', err)
        }
      })
      this.siteListGet({
        pagination: this.siteTableConfig.pagination,
        filter: this.siteTableConfig.filter
      })
    },
    async saveHandler () {
      this.$v.addOrEditForm.$touch()
      if (!this.$v.addOrEditForm.$error) {
        this.loadingSave = true
        await this.$api({
          method: 'put',
          url: `/mdm/item/site/add`,
          params: {
            itemId: this.id,
            siteId: this.addOrEditForm.siteId,
            groupId: this.addOrEditForm.groupId,
            typeId: this.addOrEditForm.typeId
          },
          emulateJSON: true,
          useLoadLayer: true,
          successCallback: ({ data }) => {
            this.addOrEditDialog = false
            this.ticked = []
          },
          errorCallback (err) {
            console.log('未处理的业务级error：', err)
          }
        })
        this.loadingSave = false
        this.siteListGet({
          pagination: this.siteTableConfig.pagination,
          filter: this.siteTableConfig.filter
        })
      }
    },
    init () {
      this.siteListGet({
        pagination: this.siteTableConfig.pagination,
        filter: this.siteTableConfig.filter
      })
      this.baseInfoGet()
    },
    baseInfoGet () {
      this.$api({
        method: 'get',
        url: `/mdm/item/findById/${this.id}`,
        successCallback: ({ data }) => {
          this.baseInfoForm = { ...data }
        },
        errorCallback (err) {
          console.log('未处理的业务级error：', err)
        }
      })
    },
    getSideTree () {
      this.$api({
        method: 'post',
        url: '/mdm/companysite/queryNoPage',
        params: {},
        emulateJSON: true,
        useLoadLayer: true,
        successCallback: ({ data }) => {
          let company = []
          data.forEach(item => {
            let companys = {}
            companys.id = item.companyId
            companys.label = item.companyCode + ' ' + '-' + ' ' + item.companyName
            companys.companyCode = item.companyCode
            companys.children = []
            if (company.length === 0) {
              company.push(companys)
            } else {
              for (let i in company) {
                if (company[i].id !== companys.id && Number(i) === Number(company.length - 1)) {
                  company.push(companys)
                } else {
                  return
                }
              }
            }
          })
          console.log(company)
          for (let i in company) {
            for (let j in data) {
              let side = {}
              side.id = data[j].siteId
              side.label = data[j].siteCode + ' ' + '-' + ' ' + data[j].siteName
              if (company[i].id === data[j].companyId) {
                company[i].children.push(side)
              }
            }
          }
          this.siteTree = company
          // this.siteTree = [{ id: '001', label: '公司0002' }]
        },
        errorCallback (err) {
          console.log('未处理的业务级error：', err)
        }
      })
    },
    tabSelect () {
      switch (this.tabSelected) {
        // case 'tab1':
        //   this.depListGet({
        //     pagination: this.depTableConfig.pagination,
        //     filter: this.depTableConfig.filter
        //   })
        //   break
        case 'tab2':
          this.siteListGet({
            pagination: this.siteTableConfig.pagination,
            filter: this.siteTableConfig.filter
          })
          break
        // case 'tab3':
        //   this.userListGet({
        //     pagination: this.userTableConfig.pagination,
        //     filter: this.userTableConfig.filter
        //   })
        //   break
      }
    },
    add () {
      this.addOrEditForm = {
        groupId: '',
        typeId: '',
        siteId: '',
        siteName: ''
      }
      this.$v.addOrEditForm.$reset()
      this.addOrEditDialog = true
    },
    // async listGet (props) {
    //   let { page, rowsPerPage, sortBy, descending } = props.pagination, filter = props.filter
    //   await this.$api({
    //     method: 'post',
    //     url: '/mdm/site/query',
    //     params: {
    //       pageNo: page,
    //       pageSize: rowsPerPage,
    //       sort: sortBy,
    //       order: descending === true ? 'desc' : (descending === false ? 'asc' : ''),
    //       ...filter
    //     },
    //     emulateJSON: true,
    //     useLoadLayer: true,
    //     successCallback: ({ data }) => {
    //       this.total = data.total
    //       this.data = data.list
    //     },
    //     errorCallback (err) {
    //       console.log('未处理的业务级error：', err)
    //     }
    //   })
    //   this.pagination.page = page
    //   this.pagination.rowsPerPage = rowsPerPage
    //   this.pagination.sortBy = sortBy
    //   this.pagination.descending = descending
    // },
    async siteListGet (props) {
      let { page, rowsPerPage, sortBy, descending } = props.pagination, filter = props.filter
      await this.$api({
        method: 'post',
        url: '/mdm/item/site/query',
        params: {
          itemId: this.id,
          pageNo: page,
          pageSize: rowsPerPage,
          sort: sortBy,
          order: descending === true ? 'desc' : (descending === false ? 'asc' : ''),
          ...filter
        },
        emulateJSON: true,
        useLoadLayer: true,
        successCallback: ({ data }) => {
          this.siteTableConfig.total = data.total
          this.siteTableConfig.data = data.list
        },
        errorCallback (err) {
          console.log('未处理的业务级error：', err)
        }
      })
      this.siteTableConfig.pagination.page = page
      this.siteTableConfig.pagination.rowsPerPage = rowsPerPage
      this.siteTableConfig.pagination.sortBy = sortBy
      this.siteTableConfig.pagination.descending = descending
      this.siteTableConfig.filter = filter
    }
  }
}
</script>
